// JavaScript Document

$(document).ready(function() {

	//To store timeout id
	var timeoutId;
	
	
	// Disable Previous Button On Page Load
	$('.SS-prev').prop('disabled', true);	
	$('.SS-next').prop('disabled', false);	



	// Disable Previous 
	var checkPrevious = function(slideNum,containerID){
		
			if(slideNum == 0){
  				$(containerID + ' .SS-prev').prop('disabled', true);	
				}else{
				$(containerID + ' .SS-prev').prop('disabled', false);	
			};		
					
			//console.log("checkPrevious: slide="+ slideNum +" / containerID ="+containerID);
	};

	// Disable Next
	var checkNext = function(slideNum,containerID){

					
			//count the total number of nodes (SS-items)
			var countSSitems = $(containerID + ' .SS-items').children().length;

				if(slideNum+1 == countSSitems){
	  				 $(containerID + ' .SS-next').prop('disabled', true);	
				}else{
					 $(containerID + ' .SS-next').prop('disabled', false);	
				}
				
			//console.log("checkNext: slide="+slideNum+" countSSitems ="+countSSitems+" containerID ="+containerID);
	};
	

	// Accessibility: Set Focus To Main Object On Button Click
	var setFocus = function(focusOn){
            $(focusOn).attr('tabindex', -1).on('blur focusout', function () {
            // when focus leaves this element, 
            // remove the tabindex attribute
            $(this).removeAttr('tabindex');
            }).focus(); // focus on focusOn
        };
		
		
		
		
		
	// go to slide by name function
	window.gotoslide = function(filename){
	//needs "window." to make it global for onClick to work

	// if images used, find containter id
	var findid = $("img[src*='"+filename+"']").parent().parent().parent().closest("div").attr("id");	

	// if SVG used, find containter id
	if (findid == undefined){	
	var findid = $("object[data*='"+filename+"']").parent().parent().parent().parent().closest("div").attr("id");
	}

	var containerID = '#'+findid ;

	//Clear timeout if any
	clearTimeout(timeoutId);
    
	// hide current image
	$(containerID + ' .SS-item:visible').hide();
	
	// FIND OBJECT AND SHOW PARENT 
	//show image by filename
	$("img[src*='"+filename+"']").parent(".SS-item").show();
	
	//if it is an svg using object
	$("object[data*='"+filename+"']").parent().parent(".SS-item").show();

	//After item is shown, reset the index
	var indx = $(containerID + '  .SS-item:visible').index();

	var slidenumber = (indx +1);//zero based counting system
	$(containerID + ' .slidestatus').html("Slide "+slidenumber);
	
	
	var currentItem = (containerID +' .SS-item')
	//Call function to set focus to slide status
	setFocus(currentItem); 
	
	
	checkPrevious(indx,containerID);
	checkNext(indx,containerID);

	
	}//end function






	
	// ////////////////////////////////////////
	// Main Next Slide Function
	// ////////////////////////////////////////
	
	
	window.slideImage = function( step, play, id) {

	//console.log("10: start slide image (" + id + " " + step + " " +  play + ")");
    // var step is current step/image number
    if (step == undefined)	{ console.log("error"); step = 1;}
    if (play == undefined)	{ console.log("error"); play = "play";}
    if (id == undefined)	{ console.log("error"); id = "";} // do more here later :)
    
	var containerID = '#'+id ;

    //var indx = 0;
    //Clear timeout if any
    clearTimeout ( timeoutId );
	
	//Get current image's index    
	var currentItemVis = $(containerID + ' .SS-item:visible');
	var indx =  $( containerID +' .SS-item' ).index( currentItemVis  );	

	var currentItem = (containerID +' .SS-item');
	
    if (step != 0) {
    //Fadeout this item
    //$('.SS-item:visible').fadeOut(0);
    $('#' + id + ' .SS-item:visible').hide();
    //$('#' + id + ' .SS-item:visible').fadeOut(1);// Fade out is smoother for animations, but requires absolute position
    }

   indx = (indx + step);

    // Check bounds for next item
    if (indx >= $(containerID + ' .SS-item').length) {
		indx = 0;
    } else if (indx < 0) {
		indx = $('#' + id + ' .SS-item').length - 1;
    }

		//If step == 0, we don't need to do any fadein our fadeout
		if (step != 0) {
		//Fadein next item
		//$('.SS-item:eq(' + indx + ')').fadeIn();
		//console.log("43: Target id " + id);
		$(containerID + ' .SS-item:eq(' + indx + ')').show();
		
		//disable next or previous buttons
		checkPrevious(indx,containerID);
		checkNext(indx,containerID);
		
		
		//Call function to set focus to slide status
		setFocus(currentItem); 
	  
    }

    // set html of status text to current step
    if (play == "stop") {
      $(containerID + ' .slidestatus').html("Slide " + (indx + 1));  
    }
	
	
	
	
	
	
	

    // get the speed from the data attributes
    // var slideshowjd = ('#' + id); //document.getElementById(id);

    //Get the "rate" from data attribute "speed".
    var rate = $(containerID).data('speed')
    if (rate == undefined) {
      rate = "100";// default
    }


    //Set timeout
    if (play == "play") {
    
	  //this makes it play only once.
      //if (indx == 0) {
        //play = "stop";
        //$(containerID + ' .slidestatus').html('Stopped');
      //}

      //timeoutId = setTimeout ( slideImage, rate );
      timeoutId = setTimeout(function() {
      slideImage(1, play, id);
      }, rate)

      //set html of status text
      $(containerID + ' .slidestatus').html('Playing');
    }

	

	

  };

  
  
  	
/////////  SVG highlights called from AI svg interactivity with:
//  window.parent.highlightsvg(evt);

window.highlightsvg = function(evt){
evt.target.style.cursor='pointer';
evt.target.setAttribute('opacity', '.5');
evt.target.setAttribute('stroke-width', '2');
evt.target.setAttribute('stroke', 'red');

	};
window.highlightsvgoff = function(evt){
evt.target.style.cursor='pointer';
evt.target.setAttribute('opacity', '100');
evt.target.setAttribute('stroke-width', '1');
evt.target.setAttribute('stroke', '#778CE0');

//evt.target.setAttribute('fill', 'yellow');
	};
  
  
  
  
  
/////////  Button listeners

  // When PREV button is clicked
  $('.SS-prev').click(function() {
    //get parent id
    var id = $(this).closest("div").attr("id");
    //slideImage with step = -1
    slideImage(-1, "stop", id);
  });
  
  
  // When NEXT button is clicked
  $('.SS-next').click(function() {
    //get parent id
    var id = $(this).closest("div").attr("id");
    //slideImage with step = 1
    slideImage(1, "stop", id);
  });

  
   // When PLAY button is clicked
  $('.SS-play').click(function() {
    //get parent id
    var id = $(this).closest("div").attr("id");
    //Start slide image
    slideImage(0, "play", id);
  });

  
  // When PAUSE button is clicked
  $('.SS-pause').click(function() {
    //Clear timeout
    clearTimeout(timeoutId);
    //get parent id
    var id = $(this).closest("div").attr("id");
    //set status text to paused
    $("#"+id + ' .slidestatus').html('Paused');
  });






}); // end doc ready


